import os
import pandas as pd
from mailmerge import MailMerge
import time
# 自定义包
import config
import utils

def msds_mailmerge(template,productinfo,msds_info,document_type):

    document = MailMerge(template)
    document.merge(ProductName = productinfo["Product Name"],
                    ProductCode = productinfo["Product Code"],
                    DocumentType = config.DOC_TYPE_DICT[document_type],
                    MonthYear = productinfo["Doc date"],
                    Ingredient = msds_info['Composition'],
                    Odor = msds_info['Odor'],
                    Appearance = msds_info['Appearance'],
                    )
    fname = 'BKD - {} {}.docx'.format(productinfo["Product Code"],document_type)
    save_path = utils.set_save_path(productinfo)

    filename = os.path.join(save_path,fname)
    document.write(filename)

    return filename

def validate_statement_data(df):
    msds_info = {'Composition':'ingredient',
                'Odor':'Characteristic odor',
                'Appearance':'Characteristic appearance'}
    
    error_list = []
    for i in msds_info.keys():
        if i in df["Item"].values:
            msds_info[i] = df[df["Item"]==i]["Target"].values[0]
        else:
            error_list.append(i)
    return msds_info,error_list

def bkd_msds(df,msds_info):
    msds_us,msds_eu = '',''
    
    productinfo = {"Product Code":df.iloc[0,0],
                "Product Name":df.iloc[0,1],
                "Doc date":time.strftime("%b %Y", time.localtime())
                }
    
    msds_template_path = config.TEMPLATE_PATH
    msds_eu_template = os.path.join(msds_template_path,'BKD - MSDS EU template.docx')
    msds_us_template = os.path.join(msds_template_path,'BKD - MSDS US template.docx')
    #print(msds_eu_template,'\n',msds_us_template)
    
    if os.path.isfile(msds_us_template):
        with open (msds_us_template, 'rb') as f:
            msds_us = msds_mailmerge(f,productinfo,msds_info,'MSDS US')
            print('msds us')
    else:
        print('BKD - {} template.docx not found'.format(msds_us_template))
    
    if os.path.isfile(msds_eu_template):
        with open (msds_eu_template, 'rb') as f:
            msds_eu = msds_mailmerge(f,productinfo,msds_info,'MSDS EU')

    else:
        print('BKD - {} template.docx not found'.format(msds_eu_template))

    return msds_us,msds_eu

def write_msds(productcode):
    df_raw = utils.validate_product_info()
    df = df_raw.copy()
    df = df[df["Product Code"] == productcode]
    df = df.reset_index(drop=True)
    msds_info,error_list = validate_statement_data(df)
    if error_list !=[]:print(error_list)
    msds_us,msds_eu = bkd_msds(df,msds_info)
    return msds_us,msds_eu,error_list

if __name__ == "__main__":
    productcode = 'SR4000'
    msds_us,msds_eu = write_msds("SR4000")
    print(msds_us,'\n',
          msds_eu,)